package com.itheima.web;

import com.itheima.service.BrandService;
import com.itheima.service.impl.BrandServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * 替换HttpServlet 根据请求的最后一段路径进行分发
 */

public class BaseServlet extends HttpServlet {

    //根据请求的最后一段路径进行分发
    private BrandService brandService = new BrandServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        //获取请求路径
        String uri = req.getRequestURI();//brand-demo/brand/selectAll
        //获取最后一段路径，方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index + 1);

        //执行方法
        //①获取BrandServlet / UserServlet的字节码对象 Class
        //this的含义 谁调用我,我代表谁（this 所在的方法）  我（this)代表谁
        //System.out.println(this);//BrandServlet? BaseServlet? HttpServlet? #BrandServlet
            /*
            浏览器访问：
            http://localhost:8080/brand-case/brand/selectAll
            http://localhost:8080/brand-case/user/selectAll
            控制台输出：
            信息: Starting ProtocolHandler ["http-bio-8080"]
            com.itheima.web.BrandServlet@3697cb3
            com.itheima.web.UserServlet@4ad3e35e*/
        Class<? extends BaseServlet> cls = this.getClass();

        try {
            //②获取方法Method对象
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //③执行方法
            method.invoke(this, req, resp);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}